import 'dart:math';

import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/ui_const_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint_list/bean/list_config_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/map_tool/bean/menu_item.dart';
import 'package:dk_flutter_module_sale/thirdParty/src/gzx_dropdown_header.dart';
import 'package:dk_flutter_module_sale/thirdParty/src/gzx_dropdown_menu.dart';
import 'package:dk_flutter_module_sale/thirdParty/src/gzx_dropdown_menu_controller.dart';
import 'package:flutter_dk_form/src/widgets/widget_pulldown_select_item.dart';
import 'package:flutter_dk_form/src/widgets/widget_row_unedit_item.dart';
import 'package:flutter_dk_form/src/widgets/widget_single_input_item.dart';
import 'package:flutter/cupertino.dart';

@ARoute(url: CommonWidgetRoute.COMMON_ADD_GOAL_HOUSE_SOURCE)
class PageAddHouseSource extends CommonPage {
  final BoostRouteOption option;
  PageAddHouseSource(this.option) : super();
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    pageBloc.switchPage(AddHouseSourceWidget(pageBloc));
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final double collapsedHeight;
  final double paddingTop;
  final Widget child;

  StickyTabBarDelegate({this.paddingTop, this.collapsedHeight, this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    debugPrint("高度为：${this.collapsedHeight + this.paddingTop}");
    return Container(
      child: Stack(
        children: <Widget>[
          this.child,
        ],
      ),
    );
  }

  @override
  double get maxExtent => this.collapsedHeight + this.paddingTop;

  @override
  double get minExtent => this.collapsedHeight + this.paddingTop;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

// ignore: must_be_immutable
class AddHouseSourceWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  BoostRouteOption option;
  AddHouseSourceWidget(this.pageBloc);
  @override
  AddHouseSourceState createState() {
    return AddHouseSourceState(this.pageBloc);
  }
}

class SortCondition {
  String name;
  bool isSelected;
  SortCondition({this.name, this.isSelected});
}

class AddHouseSourceState extends State<AddHouseSourceWidget>
    with SingleTickerProviderStateMixin {
  CommonPageBloc pageBloc;
  //面积
  TextEditingController areaController = TextEditingController(text: "");
  FocusNode areaFocusNode = FocusNode();
  //价格
  TextEditingController priceController = TextEditingController(text: "");
  FocusNode priceFocusNode = FocusNode();
  //楼层
  TextEditingController floorController = TextEditingController(text: "");
  FocusNode floorFocusNode = FocusNode();
  //卧室
  TextEditingController roomController = TextEditingController(text: "");
  FocusNode roomFocusNode = FocusNode();

  List<String> _dropDownHeaderItemStrings = ['全城', '距离近'];
  List<GZXDropDownHeaderItem> _headerItems;
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  List<SortCondition> _brandSortConditions = [];
  List<SortCondition> _distanceSortConditions = [];
  SortCondition _selectBrandSortCondition;
  SortCondition _selectDistanceSortCondition;

  DkEasyRefreshController easyRefreshController;

  final double _dropDownCellHeight = 50.0;
  final double _dropDownHeaderHeight = 50.0;
  final double navigationBarHeight = 44.0;
  int datas = 16;

  bool isShow = false;
  double maskHeight = 0.0;
  var _scaffoldKey = new GlobalKey<ScaffoldState>();

  final List<Color> colorList = [
    Colors.red,
    Colors.orange,
    Colors.green,
    Colors.purple,
    Colors.blue,
    Colors.yellow,
    Colors.pink,
    Colors.teal,
    Colors.deepPurpleAccent
  ];

  AddHouseSourceState(this.pageBloc);

  @override
  void initState() {
    super.initState();
    easyRefreshController = DkEasyRefreshController();
    _brandSortConditions.add(SortCondition(name: '全部', isSelected: true));
    _brandSortConditions.add(SortCondition(name: '金逸影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城2', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城9', isSelected: false));
    _selectBrandSortCondition = _brandSortConditions[0];

    _distanceSortConditions.add(SortCondition(name: '距离近', isSelected: true));
    _distanceSortConditions.add(SortCondition(name: '价格低', isSelected: false));
    _distanceSortConditions.add(SortCondition(name: '价格高', isSelected: false));
    _selectDistanceSortCondition = _distanceSortConditions[0];

    //下拉菜单
    _headerItems = List<GZXDropDownHeaderItem>();
    for (int i = 0; i < 2; i++) {
      GZXDropDownHeaderItem item;
      if (i == 0) {
        item = GZXDropDownHeaderItem(
            _dropDownHeaderItemStrings[0],
            TextStyle(
              color: Color(0xFF666666),
              fontSize: 14,
            ),
            false,
            Color(0xFF666666));
      } else {
        item = GZXDropDownHeaderItem(
            _dropDownHeaderItemStrings[1],
            TextStyle(
              color: Color(0xFF666666),
              fontSize: 14,
            ),
            false,
            Color(0xFF666666));
      }
      _headerItems.add(item);
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: SafeArea(
        bottom: true,
        child: Scaffold(
          key: _scaffoldKey,
          /*      appBar: DkAppBar(DKAppBarParams.withBackNoMenu(pageBloc.context,
              titleContent: "添加目标房源")),
*/
          appBar: PreferredSize(
              child: AppBar(
                brightness: Brightness.dark,
                title: Text("添加目标房源"),
                backgroundColor: Theme.of(context).primaryColor,
                elevation: 0,
              ),
              preferredSize: Size.fromHeight(navigationBarHeight)),
          backgroundColor: Colors.white,
          resizeToAvoidBottomPadding: true,
          body: Stack(
            alignment: Alignment.topLeft,
            children: <Widget>[
              NotificationListener(
                onNotification: (ScrollNotification notification) {
                  double pix = notification.metrics.pixels;
                  if(pix > 0) {
                    debugPrint("移动了距离: ${pix}");
                  }
                  return true;
                },
                child: DkRefreshListWidget.custom(
                    controller: easyRefreshController,
                    onRefresh: refreshList,
                    onLoad: null,
                    emptyWidget: null,
                    slivers: <Widget>[
                      /*
                      SliverToBoxAdapter(
                        child: Container(
                          color: Colors.orange,
                          height: 100,
                        ),
                      ),
                     */
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: DkFixedCeilingHoveringSilverDelegate(
                            _dropDownHeaderHeight, (BuildContext context) {
                          return buildFilterMenuHeadWidget();
                        }),
                      ),

                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                              (BuildContext context, int index) {
                            return Container(
                              height: 100,
                              width: double.infinity,
                              color: UIConstBean.RandomColor(),
                              child: Text(index.toString()),
                            );
                          },
                          childCount: datas,
                        ),
                      ),
                    ]),
              ),

              /*

              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  //buildFilterMenuHeadWidget(),
                  CustomScrollView(
                    slivers: <Widget>[
                      SliverToBoxAdapter(
                        child: Padding(
                          padding: EdgeInsets.all(0),
                          child: Container(
                            color: Colors.greenAccent,
                            height: 60,
                            width: double.infinity,
                          ),
                        ),
                      ),
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: StickyTabBarDelegate(
                          collapsedHeight: 0,
                          paddingTop: _dropDownHeaderHeight,
                          child: Container(
                            width: double.infinity,
                            color: Colors.black,
                            child: buildFilterMenuHeadWidget(),
                          ),
                        ),
                      ),

                      SliverFixedExtentList(
                        delegate: SliverChildBuilderDelegate(
                              (context, index) => Container(color: colorList[index]),
                          childCount: colorList.length,
                        ),
                        itemExtent: 100,
                      ),

                    ],
                  ),
                  Container(
                    color: Colors.greenAccent,
                    height: 40,
                    width: double.infinity,
                  ),
                ],
              ),
             */
              buildDropDownMenu(),
              Offstage(
                offstage: !isShow,
                child:            InkWell(
                  onTap: (){
                    isShow = !isShow;
                    _dropdownMenuController.hide();
                    setState(() {
                    });
                  },
                  child:  Container(
                    height: maskHeight,
                    color: Color.fromRGBO(0, 0, 0, 0.5),
                  ),
                ),
              ),
            ],
          ),
          /*
          body: ListView.builder(
              itemCount: 7,
              itemBuilder: (BuildContext buildContext, int index) {
                return getItemWidget(index);
              }),
           */
        ),
      ),
    );
  }

  Future<void> loadMore() async {
    setState(() {
      datas = 10;
      easyRefreshController.finishLoad(success: true, noMore: false);
    });
  }

  Future<void> refreshList({showLoading = false}) {
    Future.delayed(Duration(seconds: 1), () {
      setState(() {
        datas = 10;
        easyRefreshController.finishRefresh(success: true);
      });
    });
    return new Future.value();
  }

  Widget buildFilterMenuHeadWidget() {
    GZXDropDownHeader menuWidget = GZXDropDownHeader(
      items: _headerItems,
      stackKey: _scaffoldKey,
      navigationBarHeight: navigationBarHeight,
      tapCallback: (double height) {
          setState(() {
            isShow = !isShow;
            maskHeight = height;
            debugPrint("高度: $maskHeight----$isShow");
          });
      },
      // controller用于控制menu的显示或隐藏
      controller: _dropdownMenuController,
      // 当点击头部项的事件
      onItemTap: (index, updateIndex) {
        for (int i = 0; i < _headerItems.length; i++) {
          GZXDropDownHeaderItem item = _headerItems[i];
          item.isSelected = (i == index) ? true : false;
        }
        if (updateIndex != -1) {
          _dropdownMenuController.show(updateIndex);
        }
        isShow = true;
        setState(() {});
      },
      height: _dropDownHeaderHeight,
    );
    return menuWidget;
  }

  Widget buildDropDownMenu() {
    List<GZXDropdownMenuBuilder> widgets = _dropDownHeaderItemStrings.map((i) {
      return GZXDropdownMenuBuilder(
          dropDownHeight: ((i == 0)
                  ? _brandSortConditions.length
                  : _distanceSortConditions.length) *
              _dropDownCellHeight,
          dropDownWidget: _buildOneColumnWidget(
              ((i == 0) ? _brandSortConditions : _distanceSortConditions),
              (SortCondition value) {
            _dropdownMenuController.hide();
            isShow = false;
            setState(() {});
          }));
    }).toList();
    // 下拉菜单
    return GZXDropDownMenu(
      controller: _dropdownMenuController,
      animationMilliseconds: 20,
      maskCallback: () {
        _dropdownMenuController.hide();
        isShow = false;
        setState(() {});
      },
      //下拉菜单，高度自定义,选择后调用_dropdownMenuController.hide();即可
      menus: widgets,
    );
  }

  Widget _buildOneColumnWidget(
      List<SortCondition> items, void itemOnTap(SortCondition subItemBean)) {
    return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        itemCount: items.length,
        itemBuilder: (BuildContext context, int index) {
          SortCondition itemBean = items[index];
          return InkWell(
            onTap: () {
              for (var value in items) {
                value.isSelected = false;
              }
              itemBean.isSelected = true;
              itemOnTap(itemBean);
            },
            child: Container(
                // color: Color(0xFFffffff),
                color: index == 0
                    ? Color.fromRGBO(255, 0, 0, 0.2)
                    : UIConstBean.RandomColor(),
                height: _dropDownCellHeight,
                alignment: Alignment.center,
                child: Center(
                  child: Text(
                    itemBean.name,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Color(0xFF666666),
                    ),
                  ),
                )),
          );
        });
  }

  Widget getItemWidget(int index) {
    Widget itemWidget;
    switch (index) {
      case 0:
        {
          itemWidget = RowUnEditItemWidget(
            title: "小区",
            content: "角门9号院",
            isLine: true,
          );
          break;
        }
      case 1:
        itemWidget = RowUnEditItemWidget(
          title: "参考来源",
          content: "链家",
          isLine: true,
        );
        break;
      case 2:
        itemWidget = SingleInputItemWidget(
          title: "面积",
          placeholder: "请输入面试",
          controller: areaController,
          focusNode: areaFocusNode,
          isLine: true,
          inputCharFormatterType:
              InputCharFormatterType.InputCharFormatterDecimal,
        );
        break;
      case 3:
        itemWidget = SingleInputItemWidget(
          title: "价格",
          placeholder: "请输入价格",
          controller: priceController,
          focusNode: priceFocusNode,
          isLine: true,
          inputCharFormatterType:
              InputCharFormatterType.InputCharFormatterDigital,
        );
        break;
      case 4:
        itemWidget = SingleInputItemWidget(
          title: "楼层",
          placeholder: "请输入楼层",
          controller: floorController,
          focusNode: floorFocusNode,
          isLine: true,
        );
        break;
      case 5:
        itemWidget = SingleInputItemWidget(
          title: "卧室",
          placeholder: "请输入卧室数量",
          controller: roomController,
          focusNode: roomFocusNode,
          isLine: true,
          inputCharFormatterType:
              InputCharFormatterType.InputCharFormatterDigital,
        );
        break;
      case 6:
        itemWidget = PulldownSelectItemWidget(
          title: "分配BD",
          isLine: false,
          placeholder: "请选择执行销售",
          tapCallback: () {
            debugPrint("下拉选择");
          },
        );
        break;
    }
    return itemWidget;
  }

  @override
  void dispose() {
    super.dispose();
  }
}
